/*
 *退款单详情页面
 */

var sysRefundDetail = {};
sysRefundDetail.operation = {};
$sysRefundSkuTable = null;
$sysReturnSkuTable = null;

$(function () {
    // 根据退款单ID获取退款明细信息
    var returnData = sysRefundDetail.getDetailInfoByRefundId();

    if (!!returnData) {
        // 初始化基本信息页
        sysRefundDetail.initBasePage(returnData);
        // 初始化商品信息表格
        sysRefundDetail.initRefundGoods(returnData);
        // 初始化退入信息表格
        sysRefundDetail.initReturnGoods(returnData);
        // 初始化内部便签
        sysRefundDetail.initNotePage(returnData);
    }

    $('a[data-toggle="tab"]').on('shown.bs.tab', function (e) {

        switch ($(this).attr("id")) {
            case "noteInfoTabLink": {

                window.frames["noteIframe"].window.$noteTable.ajax.reload().draw();
                break;
            }

        }
        ;

        var tables = $.fn.dataTable.tables({
            visible: true,
            api: true
        });
        if (tables.length > 0) {
            $(tables).DataTable().columns.adjust();
        }
    });
});

var getRefundChannelInfo = function (data) {
    var returnValue = "";
    if (data == "online") {
        returnValue = '线上';
    } else {
        returnValue = '线下';
    }
    return returnValue;
};

var getTradeStatusInfo = function (data) {
    var returnValue = "-";
    if (data == "EC_WAIT_BUYER_PAY") {
        returnValue = "等待买家付款";
    } else if (data == "EC_WAIT_SELLER_SEND") {
        returnValue = "等待卖家发货";
    } else if (data == "EC_TRADE_PARTIALLY_SEND") {
        returnValue = "交易部分发货";
    } else if (data == "EC_TRADE_ALL_SEND") {
        returnValue = "交易全部发货";
    } else if (data == "EC_TRADE_FINISHED") {
        returnValue = "交易成功";
    } else if (data == "EC_TRADE_CANCELED") {
        returnValue = "交易取消";
    }
    return returnValue;
};

sysRefundDetail.initBasePage = function (pageData) {
    // 基本信息页退款信息赋值
    for (var index in pageData) {
        if ("refundChannel" == index) {
            pageData[index] = getRefundChannelInfo(pageData[index]);
        } else if ("ecOrderStatus" == index) {
            //
            pageData[index] = getTradeStatusInfo(pageData[index]);
        }
        $("#tab-basicInfo").find("#" + index).html(pageData[index] || "-");
    }

    // 基本信息页退货信息赋值
    for (var index in pageData.sysReturnVO) {
        var $Obj = $("#tab-basicInfo").find("#" + index);
        if (!$Obj.html()) {
            $("#tab-basicInfo").find("#" + index).html(pageData.sysReturnVO[index] || "-");
        }
    }
    // 平台退款状态、货物状态单独设置
    $("#ecRefundStatus").html(pageData.ecRefundStatusString || "-");
    $("#goodStus").html(pageData.goodsStatusString || "-");
    $("#refundFee").html(numberParser(pageData.refundFee) || "-");
};
sysRefundDetail.initRefundGoods = function (pageData) {
    if (null == $sysRefundSkuTable) {
        $sysRefundSkuTable = $("#sysRefundSkuTable").DataTable({
            "processing": true,
            "dom": '<"bottom"rtflp>',
            "searching": false,
            "paging": false,

            "scrollX": "100%",
            "scrollXInner": "110%",
            "scrollCollapse": false,
            "destroy": true,
            "deferRender": true,

            "ordering": false,
            "columns": [{
                "data": "goodsCode"
            }, {
                "className": "truncate-text tooltip-column-detail",
                "data": "goodsName"
            }, {
                "data": "skuCode"
            }, {
                "className": "truncate-text tooltip-column-detail",
                "data": "skuName"
            }, {
                    "data": "ecItemCode",
                    "orderable": false
                }, {
                    "className": "truncate-text tooltip-column-detail",
                    "data": "ecItemName"
                }, {
                    "data": "ecSkuCode",
                    "orderable": false
                }, {
                    "className": "truncate-text tooltip-column-detail",
                    "data": "ecSkuName",
                    "orderable": false
                }, {
                    "data": "refundFee",
                    "className": "text-right",
                    "orderable": false,
                    "render": numberParser
                }, {
                    "data": "factUnitPrice",
                    "orderable": false,
                    "className": "text-right",
                    "render": numberParser
                }
                , {
                    "className": "text-right",
                    "data": "actualAmount",
                    "orderable": false,
                    "render": numberParser
                }, {
                    "className": "text-right",
                    "data": "actualPayPrice",
                    "orderable": false,
                    "render": numberParser
                }, {
                    "className": "text-right",
                    "data": "divideOrderFee",
                    "orderable": false,
                    "render": numberParser
                }]
        }).on('draw.dt', function () {
            $("#sysRefundSkuTable").tooltip({
                selector: ".tooltip-column-detail",
                container: "body",
                title: function () {
                    if ($(this)[0].scrollWidth > $(this).outerWidth()) {
                        return $(this).text();
                    }
                }
            });
            $("#sysRefundSkuTable").DataTable().columns.adjust();
            
            // 如果是待审核，就显示SN号页面
//            if(window.parent.window.$("li.active:eq(0)").find("a").attr("id")=="waitingAuth"){
//                $sysRefundSkuTable.column(4).visible(true);
//            }
        });
    }
    ;

    // 从returnskulist中把退款数据取出来，放到列表中
    for (var i = 0, j = pageData.orderSkuList.length; i < j; i++) {
        pageData.orderSkuList[i].refundFee = sysRefundDetail.getRefundFee(pageData.sysRefundSkuList, pageData.orderSkuList[i].orderSkuId);
    }
    $sysRefundSkuTable.rows.add(pageData.orderSkuList).draw();

};

sysRefundDetail.getRefundFee = function (dataList, orderSkuId) {
    
    var returnValue = 0;
    for (var index in dataList) {
        if (dataList[index].sourceSkuId === orderSkuId) {
            returnValue = dataList[index].refundFee || 0;
            break;
        }
    }
    return numberParser(returnValue);
}

sysRefundDetail.initReturnGoods = function (pageData) {
    //
    var returnSkuList = [];
    var tempReturnItem = {};
    var tempReturnSku = {};
    for (var i = 0, j = pageData.sysReturnSkuList4Detail.length; i < j; i++) {
        var returnSkuItem = {};
        returnSkuItem = pageData.sysReturnSkuList4Detail[i];    // 相关商品信息
        tempReturnItem = returnSkuItem.sysReturnVO; // 相关退款单单据
        //
//        returnSkuItem.finishType = tempReturnItem.finishType;
        returnSkuItem.inventoryType = tempReturnItem.inventoryType;
        returnSkuItem.returnStatus = tempReturnItem.returnStatus;
        returnSkuItem.isCancel = tempReturnItem.isCancel;
        returnSkuItem.returnCode = tempReturnItem.returnCode;
        returnSkuItem.lgstName = tempReturnItem.lgstName;
        returnSkuItem.lgstNo = tempReturnItem.lgstNo;

        returnSkuItem.qty = returnSkuItem.qty || 0;
        returnSkuItem.factUnitPrice = returnSkuItem.divideGoodsFee || 0;

        returnSkuItem.divideOrderFee = parseInt(returnSkuItem.qty) * parseFloat(returnSkuItem.factUnitPrice);
        returnSkuItem.createTime = tempReturnItem.createTime;
        returnSkuItem.finishTime = tempReturnItem.finishTime;
        returnSkuList.push(returnSkuItem);
    }
    if (null == $sysReturnSkuTable) {
        $sysReturnSkuTable = $("#sysReturnSkuTable").DataTable({
            "processing": true,
            "dom": '<"bottom"rtflp>',
            "searching": false,
            "scrollCollapse": false,
            "destroy": true,
            "paging": false,

            "scrollX": "100%",
            "scrollXInner": "110%",
            "scrollCollapse": false,
            "destroy": true,
            "deferRender": true,
            "ordering": false,
            "columns": [
//                {
//                "data": "finishType",
//                "render": function (data) {
//                    var returnValue = "-";
//                    if (data == "e") {
//                        returnValue = '<span class="badge badge-orange"> </span>';
//                    }
//                    return returnValue;
//                }
//            }
                {
                    "data": "inventoryType",
                    "render": function (data) {
                        var returnValue = "正品";
                        if (data == "cp") {
                            returnValue = '次品';
                        }
                        return returnValue;
                    }
                }
                , {
                "data": "returnStatus",
                "render": function (data, type, row, meta) {
                    var returnValue = "状态未知";
                    if (row.isCancel == "y") {
                        returnValue = "已废弃";
                    } else {
                        if (data == "a") {
                            returnValue = "待审核";
                        } else if (data == "f") {
                            returnValue = "待收货";
                        } else if (data == "z") {
                            returnValue = "已完成";
                        }
                    }
                    return returnValue;
                }
            }, {
                "data": "returnCode"
            }, {
                "data": "lgstName"
            }, {
                "data": "lgstNo"
            }
                , {
                    "data": "goodsCode",
                    "orderable": false
                }, {
                    "className": "truncate-text tooltip-column-detail",
                    "data": "goodsName",
                    "orderable": false
                }, {
                    "data": "skuCode",
                    "orderable": false
                }, {
                    "className": "truncate-text tooltip-column-detail",
                    "data": "skuName"
                }
                , {
                    "data": "qty",
                    "orderable": false,
                    "className": "text-right"
                }
                , {
                    "className": "text-right",
                    "data": "factUnitPrice",
                    "orderable": false,
                    "render": numberParser
                }, {
                    "className": "text-right",
                    "data": "divideOrderFee",
                    "orderable": false,
                    "render": numberParser
                }, {
                    "className": "text-right",
                    "data": "createTime"
                }, {
                    "className": "text-right",
                    "data": "finishTime"
                }, {
                    "data": "sn",
                    "orderable": false
                }]
        }).on('draw.dt', function () {
            $("#sysReturnSkuTable").tooltip({
                selector: ".tooltip-column-detail",
                container: "body",
                title: function () {
                    //
                    if ($(this)[0].scrollWidth > $(this).outerWidth()) {
                        return $(this).text();
                    }
                }
            });
        });
        ;
    }
    $sysReturnSkuTable.rows.add(returnSkuList).draw();
};

sysRefundDetail.getDetailInfoByRefundId = function () {
    var refundId = extractParam("refundId");
    if (!!refundId) {
        return sysRefundDetail.operation.getRefundInfo(refundId);
    }
};

/*
 * 获取退款单的明细信息，包括基本信息，退款明细信息，退货基本信息
 */
sysRefundDetail.operation.getRefundInfo = function (sysRefundId) {
    var returnData = null;
    var loading = window.top.window.getIndexBusyOverlay();
    $.ajax({
        type: "GET",
        url: "/sysRefundManager/sysRefundFullDetail.action",
        contentType: "application/json;charset=utf-8",
        data: {
            "sysRefundId": sysRefundId
        },
        dataType: "json",
//        async: false,
        beforeSend:function(){
            if(loading) {
            	loading.settext("正在处理中，请稍后...");
            }
        },
        success: function (data) {
        	loading.remove();
            if (data.result == "success") {
                returnData = data.data;
            } else {
                window.top.window.showModalAlert(data.msg);
            }
        },
        error: function (XMLHttpRequest, textStatus) {
        	loading.remove();
            if (XMLHttpRequest.status == 500) {
                var result = eval("(" + XMLHttpRequest.responseText + ")");
                window.top.window.showScoMessage('error', result.errorObject.errorText);
            }
        }
    });
    return returnData;
};

// 初始化内部便签
sysRefundDetail.initNotePage = function () {
    var refundId = extractParam("refundId");
    var ifmSrc = "/views/base/note/notelist.html?busiKey=" + refundId;
    $("#noteIframe").attr("src", ifmSrc);
};

// ====== 公共方法 ======
//获取页面参数
function GetArgsFromHref(sHref, sArgName) {
    var args = sHref.split("?");
    var retval = "";

    if (args[0] == sHref) /*参数为空*/
    {
        return retval;
        /*无需做任何处理*/
    }
    var str = args[1];
    args = str.split("&");
    for (var i = 0; i < args.length; i++) {
        str = args[i];
        var arg = str.split("=");
        if (arg.length <= 1) continue;
        if (arg[0] == sArgName) retval = arg[1];
    }
    return retval;
}

function extractParam(paramName) {
    var returnString = "";
    var str = window.location.search;
    if (!!str) {
        returnString = GetArgsFromHref(str, paramName);
    }
    return returnString;
}


var numberParser = function(data){
    var returnValue = "-";
    var numberData = parseFloat(data);
    if(numberData===+numberData){
        returnValue = numberData.toFixed(2);
    }
    return returnValue;
};